<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/1/15
 * Time: 23:05
 */
namespace app\admin\logic;




use app\admin\logic\mqlogic\DirectPublisher;
use app\admin\logic\mqlogic\RateExportConsumer;
use app\admin\logic\statistics\RateStatistics;
use app\admin\model\rate\File;
use app\common\model\Company;
use think\exception\ValidateException;

class RateService
{
    private static $new; //申请一个私有的静态成员变量来保存该类的唯一实例
    static $exchange = 'rate_export';  //扇形交换机
    static $queue = 'rate_export_1';
    static $routeKey = 'rate_export_1';
    const TITLE_ARR = [
        '扣缴义务人识别号（社会信用代码）'         => [1, 2, 9],  //0为开始  1为结束
        '91120116MA06GUUW42'                 => [3,3, 9],
        '扣缴义务人名称'                       =>[4,4, 20],
        '天津合众共享经济信息咨询有限公司'        => [5,5, 20],
        '行业'                              => [6,6, 9] ,
        '其他技术推广服务'                   =>[7,7, 9],
        '行政区划'                          =>[8,8, 10],
        '滨海新区'                         =>[9,10,9],
        '街道乡镇'                         =>[11,11,9],
        '中关村科技园'                      => [12,13,10],
        '税务机关'                         =>[14,14,9] ,
        '滨海新区中关村科技园税务所'           => [15,15,15]
    ];
    const SUBMIT = [
        'author' =>'天津合众共享经济信息咨询有限公司',
        'subject' =>'天津合众共享经济信息咨询有限公司',
        'title' =>'税务导出',
    ];
    const FIELD_MAP = ['序号', '姓名', '身份证件类型','身份证件号码', '国籍（地区）','联系电话','生产经营地行政区划','应税收入','应税所得率','计税依据','税率', '速算扣除数', '应纳税额', '累计已缴纳税额', '本期应补退税额'];
    const SUM_TITLE = ['身份证', '姓名', '本月次数', '本月累计众包费', '本年次数', '本年累计众包费'];
    private function __construct() {

    }


    public static function instance () { //声明一个静态公共方法，供外部获取唯一实例
        if (!(self::$new instanceof self)) {
            self::$new = new self;
        }
        return self::$new;
    }

    /**
     * 直连交换机
     */
    public function publisher($message) {
        $objMq = new DirectPublisher(config('site.rabitmqconfig'));
        $objMq->setExchange(self::$exchange)->setQueue(self::$queue)->setBindKey(self::$routeKey);

        $objMq->publish($message);
    }

    /**
     * 打款消费者
     */
    public function consumer() {
        $config = config('site.rabitmqconfig');
        $objConsumer = new RateExportConsumer($config);
        $objConsumer->setQueue(self::$queue)->consume();

        return true;
    }


    /**
     * 生成税率 报表
     * @param array $where
     * @param string $timeStr
     * @param int $company_id
     * @param int $type
     * @return boolean
     */
    public function export($where = [], $timeStr = '', $company_id = 0,$type = 2,$exname = '') {
        $company_name = '';
        if ($company_id) {
            $where['company_id'] = $company_id;
            $company_name = Company::where(['id' => $company_id])->value('name');
            $name = $company_name . '/' . $timeStr . '/' . date("YmdHis");
        } else {
            $name = $timeStr . '/' . date("YmdHis");
        }
        //判断目录是否存在 如果目录
        if ($timeStr == '') {
            throw new ValidateException('请选择时间');
        }
        $titleArr = self::TITLE_ARR;
        $submit = self::SUBMIT;
        $conf = config('site.export_config');
        $rateSta = RateStatistics::instance()->setYearToMonthTime($timeStr); //设置时间
        $list = $rateSta->getList($where);
        //list($sheetName, $sort, $line, $sheet) = [ $timeStr . '-表0', 1, 1, 0]; //初始化变量
        list($sheetName, $sort, $line, $sheet) = [ $timeStr . '-税务报表', 1, 1, 0]; //初始化变量
        $excel = ExportService::instance()->setTitles($submit);

        //初始化
        $excel->createSheet($sheetName, $sheet)->setSheetHeader($line, $titleArr);
        $fieldMap = self::FIELD_MAP;
        $line++;
        $excel->insertValues($line, $fieldMap);
        foreach ($list as $k => $v) {
            $line ++;
            $values = $rateSta->getExportValues($sort, $v);
            $excel->insertValues($line, $values);
            $sort ++;
        }
        //加入sheet1 作为统计模块
        $sum_line = 2;
        $excel->createSheet($timeStr . '-统计信息', ++$sheet);
        $excel->setSheetHeader(1, [
            '如果导出税务列表数量与线上数据不符合，可能原因：1.该用户跨公司发放多次，2.纳税金额跨段'         => [1, 14],  //0为开始  1为结束
        ]);
        $excel->insertValues($sum_line, self::SUM_TITLE);
        foreach ($rateSta->sumInfo as $k => $v) {
            $sum_line ++;
            $excel->insertValues($sum_line, $v);
        }

        //每个sheet 20条数据
        /*foreach ($list as $k => $v) {
            $line ++;
            if ($sort <= $conf['rows']) {
                $values = $rateSta->getExportValues($sort, $v);
                $excel->insertValues($line, $values);
                $sort ++;
            } else {
                $sheet++;
                list($sheetName, $sort, $line) = [$timeStr . '-表'.$sheet, 1, 1]; //初始化变量
                $excel->createSheet($sheetName, $sheet)->setSheetHeader($line, $titleArr);
                $fieldMap = self::FIELD_MAP;
                $line++;
                $excel->insertValues($line, $fieldMap);
            }
        }*/

        if ($exname != '') {
            $name = $exname;
        }
        if ($type == 1) {
            $excel->output('Xlsx', $name);
        } else {
            $dir = $excel->write('Xlsx', $name);
            //导出成功  记录到
            $this->file($timeStr, $company_id, $dir, $company_name .'税务报表');
        }
        return true;
    }

    public function file($name, $company_id, $file, $dec) {
        $data['name'] = $name;
        $data['company_id'] = $company_id;
        $data['file'] = $file;
        $data['dec'] = $dec;

        $res = File::create($data);
        if ($res === false) {
            throw new ValidateException('写入文件表失败');
        }

        return true;
    }
    private function __clone() {} //声明私有的克隆方法，防止对象被克隆

    public function __sleep() { //重写__sleep方法，将返回置空，防止序列化反序列化获得新的对象
        return [];
    }
}